<template>
  <div class="excel-template-designer">
    <a-card title="Excel表格模板设计器" :bordered="false">
      <!-- 工具栏 -->
      <div class="toolbar">
        <a-space>
          <a-button type="primary" @click="addRow">
            <template #icon><icon-plus /></template>
            添加行
          </a-button>
          <a-button @click="addColumn">
            <template #icon><icon-plus /></template>
            添加列
          </a-button>
          <a-button
            @click="deleteSelectedRows"
            :disabled="selectedRowKeys.length === 0"
          >
            <template #icon><icon-delete /></template>
            删除选中行
          </a-button>
          <a-button
            @click="deleteSelectedColumns"
            :disabled="selectedColumnKeys.length === 0"
          >
            <template #icon><icon-delete /></template>
            删除选中列
          </a-button>
          <a-divider direction="vertical" />
          <a-button type="primary" @click="exportExcel">
            <template #icon><icon-download /></template>
            导出Excel
          </a-button>
          <a-button @click="saveTemplate">
            <template #icon><icon-save /></template>
            保存模板
          </a-button>
          <a-button @click="loadTemplate"> 加载模板 </a-button>
          <a-button @click="clearAll">
            <template #icon><icon-refresh /></template>
            清空
          </a-button>
        </a-space>
      </div>

      <!-- 表格编辑区域 -->
      <div class="table-container">
        <a-table
          :columns="tableColumns"
          :data="tableData"
          :pagination="false"
          :scroll="{ x: 'max-content', y: 600 }"
          :row-selection="{
            type: 'checkbox',
            selectedRowKeys,
            onChange: onRowSelectionChange,
          }"
          bordered
          size="small"
          class="editable-table"
        >
          <template #columns>
            <a-table-column
              v-for="(column, index) in tableColumns"
              :key="column.dataIndex"
              :title="column.title"
              :dataIndex="column.dataIndex"
              :width="column.width || 120"
            >
              <template #title>
                <div class="column-header">
                  <a-input
                    v-model="column.title"
                    size="small"
                    @change="updateColumnTitle(index, $event)"
                    placeholder="列标题"
                  />
                  <a-checkbox
                    v-model="selectedColumnKeys"
                    :value="column.dataIndex"
                    style="margin-left: 8px"
                  />
                </div>
              </template>
              <template #cell="{ record, rowIndex }">
                <a-input
                  v-model="record[column.dataIndex]"
                  size="small"
                  @change="updateCellValue(rowIndex, column.dataIndex, $event)"
                  placeholder="输入内容"
                />
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>

      <!-- 属性设置面板 -->
      <div class="property-panel">
        <a-card title="属性设置" size="small" style="margin-top: 16px">
          <a-form layout="inline">
            <a-form-item label="表格名称">
              <a-input v-model="templateName" placeholder="请输入表格名称" />
            </a-form-item>
            <a-form-item label="行数">
              <a-input-number
                v-model="rowCount"
                :min="1"
                :max="100"
                @change="adjustRows"
              />
            </a-form-item>
            <a-form-item label="列数">
              <a-input-number
                v-model="columnCount"
                :min="1"
                :max="26"
                @change="adjustColumns"
              />
            </a-form-item>
          </a-form>
        </a-card>
      </div>

      <!-- 预览模态框 -->
      <a-modal
        v-model:visible="previewVisible"
        title="Excel预览"
        :width="800"
        :footer="false"
      >
        <div class="preview-content">
          <a-table
            :columns="tableColumns"
            :data="tableData"
            :pagination="false"
            bordered
            size="small"
          />
        </div>
      </a-modal>

      <!-- 模板加载模态框 -->
      <a-modal
        v-model:visible="templateListVisible"
        title="选择模板"
        :width="600"
        @ok="loadSelectedTemplate"
      >
        <a-list :data="savedTemplates" size="small">
          <template #item="{ item }">
            <a-list-item>
              <a-list-item-meta
                :title="item.name"
                :description="`创建时间: ${item.createTime}`"
              />
              <template #actions>
                <a-button size="small" @click="selectTemplate(item)"
                  >选择</a-button
                >
                <a-button
                  size="small"
                  status="danger"
                  @click="deleteTemplate(item.id)"
                  >删除</a-button
                >
              </template>
            </a-list-item>
          </template>
        </a-list>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconPlus,
  IconDelete,
  IconDownload,
  IconSave,
  IconRefresh,
} from "@arco-design/web-vue/es/icon";
import * as XLSX from "xlsx";
// 移除后端API导入，使用纯前端实现

// 响应式数据
const templateName = ref("新建表格模板");
const rowCount = ref(5);
const columnCount = ref(5);
const selectedRowKeys = ref([]);
const selectedColumnKeys = ref([]);
const previewVisible = ref(false);
const templateListVisible = ref(false);
const selectedTemplate = ref(null);

// 表格数据
const tableData = ref([]);
const tableColumns = ref([]);

// 保存的模板列表
const savedTemplates = ref([]);

// 初始化表格
const initTable = () => {
  // 初始化列
  tableColumns.value = [];
  for (let i = 0; i < columnCount.value; i++) {
    const columnKey = String.fromCharCode(65 + i); // A, B, C...
    tableColumns.value.push({
      title: `列${columnKey}`,
      dataIndex: columnKey,
      width: 120,
      editable: true,
    });
  }

  // 初始化行数据
  tableData.value = [];
  for (let i = 0; i < rowCount.value; i++) {
    const row = { key: i };
    tableColumns.value.forEach((col) => {
      row[col.dataIndex] = "";
    });
    tableData.value.push(row);
  }
};

// 添加行
const addRow = () => {
  const newRow = { key: tableData.value.length };
  tableColumns.value.forEach((col) => {
    newRow[col.dataIndex] = "";
  });
  tableData.value.push(newRow);
  rowCount.value = tableData.value.length;
};

// 添加列
const addColumn = () => {
  if (columnCount.value >= 26) {
    Message.warning("最多支持26列");
    return;
  }

  const columnKey = String.fromCharCode(65 + columnCount.value);
  const newColumn = {
    title: `列${columnKey}`,
    dataIndex: columnKey,
    width: 120,
    editable: true,
  };

  tableColumns.value.push(newColumn);

  // 为所有行添加新列的数据
  tableData.value.forEach((row) => {
    row[columnKey] = "";
  });

  columnCount.value = tableColumns.value.length;
};

// 删除选中行
const deleteSelectedRows = () => {
  if (selectedRowKeys.value.length === 0) {
    Message.warning("请先选择要删除的行");
    return;
  }

  tableData.value = tableData.value.filter(
    (_, index) => !selectedRowKeys.value.includes(index)
  );
  // 重新设置key
  tableData.value.forEach((row, index) => {
    row.key = index;
  });

  selectedRowKeys.value = [];
  rowCount.value = tableData.value.length;
  Message.success("删除成功");
};

// 删除选中列
const deleteSelectedColumns = () => {
  if (selectedColumnKeys.value.length === 0) {
    Message.warning("请先选择要删除的列");
    return;
  }

  // 删除列
  tableColumns.value = tableColumns.value.filter(
    (col) => !selectedColumnKeys.value.includes(col.dataIndex)
  );

  // 删除数据中对应的列
  tableData.value.forEach((row) => {
    selectedColumnKeys.value.forEach((colKey) => {
      delete row[colKey];
    });
  });

  selectedColumnKeys.value = [];
  columnCount.value = tableColumns.value.length;
  Message.success("删除成功");
};

// 调整行数
const adjustRows = (newRowCount) => {
  const currentRowCount = tableData.value.length;

  if (newRowCount > currentRowCount) {
    // 添加行
    for (let i = currentRowCount; i < newRowCount; i++) {
      const newRow = { key: i };
      tableColumns.value.forEach((col) => {
        newRow[col.dataIndex] = "";
      });
      tableData.value.push(newRow);
    }
  } else if (newRowCount < currentRowCount) {
    // 删除行
    tableData.value = tableData.value.slice(0, newRowCount);
  }
};

// 调整列数
const adjustColumns = (newColumnCount) => {
  const currentColumnCount = tableColumns.value.length;

  if (newColumnCount > currentColumnCount) {
    // 添加列
    for (let i = currentColumnCount; i < newColumnCount; i++) {
      const columnKey = String.fromCharCode(65 + i);
      const newColumn = {
        title: `列${columnKey}`,
        dataIndex: columnKey,
        width: 120,
        editable: true,
      };

      tableColumns.value.push(newColumn);

      // 为所有行添加新列的数据
      tableData.value.forEach((row) => {
        row[columnKey] = "";
      });
    }
  } else if (newColumnCount < currentColumnCount) {
    // 删除列
    const columnsToRemove = tableColumns.value.slice(newColumnCount);
    tableColumns.value = tableColumns.value.slice(0, newColumnCount);

    // 删除数据中对应的列
    tableData.value.forEach((row) => {
      columnsToRemove.forEach((col) => {
        delete row[col.dataIndex];
      });
    });
  }
};

// 更新列标题
const updateColumnTitle = (columnIndex, event) => {
  tableColumns.value[columnIndex].title = event.target.value;
};

// 更新单元格值
const updateCellValue = (rowIndex, columnKey, event) => {
  tableData.value[rowIndex][columnKey] = event.target.value;
};

// 行选择变化
const onRowSelectionChange = (selectedKeys) => {
  selectedRowKeys.value = selectedKeys;
};

// 导出Excel
const exportExcel = () => {
  try {
    // 准备导出数据
    const exportData = {
      templateName: templateName.value || "表格模板",
      headers: tableColumns.value.map((col) => col.title),
      data: tableData.value.map((row) =>
        tableColumns.value.map((col) => row[col.dataIndex] || "")
      ),
    };

    // 使用前端XLSX库导出
    const allData = [exportData.headers, ...exportData.data];

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet(allData);

    // 设置列宽
    const colWidths = tableColumns.value.map(() => ({ wch: 15 }));
    ws["!cols"] = colWidths;

    // 添加工作表
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    // 导出文件
    XLSX.writeFile(wb, `${exportData.templateName}.xlsx`);

    Message.success("Excel导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    Message.error("导出失败，请重试");
  }
};

// 保存模板
const saveTemplate = () => {
  if (!templateName.value.trim()) {
    Message.warning("请输入模板名称");
    return;
  }

  try {
    // 保存到localStorage
    const localTemplate = {
      id: Date.now(),
      name: templateName.value,
      columns: JSON.parse(JSON.stringify(tableColumns.value)),
      data: JSON.parse(JSON.stringify(tableData.value)),
      rowCount: rowCount.value,
      columnCount: columnCount.value,
      createTime: new Date().toLocaleString(),
    };

    const templates = JSON.parse(
      localStorage.getItem("excelTemplates") || "[]"
    );
    templates.push(localTemplate);
    localStorage.setItem("excelTemplates", JSON.stringify(templates));

    // 更新模板列表
    loadSavedTemplates();

    Message.success("模板保存成功");
  } catch (error) {
    console.error("保存模板失败:", error);
    Message.error("保存模板失败，请重试");
  }
};

// 加载模板
const loadTemplate = () => {
  loadSavedTemplates();
  templateListVisible.value = true;
};

// 加载保存的模板列表
const loadSavedTemplates = () => {
  try {
    // 从localStorage获取本地模板
    const localTemplates = JSON.parse(
      localStorage.getItem("excelTemplates") || "[]"
    );
    savedTemplates.value = localTemplates;
  } catch (error) {
    console.error("加载模板列表失败:", error);
    savedTemplates.value = [];
  }
};

// 选择模板
const selectTemplate = (template) => {
  selectedTemplate.value = template;
};

// 加载选中的模板
const loadSelectedTemplate = () => {
  if (!selectedTemplate.value) {
    Message.warning("请选择一个模板");
    return;
  }

  const template = selectedTemplate.value;

  templateName.value = template.name;
  tableColumns.value = JSON.parse(JSON.stringify(template.columns));
  tableData.value = JSON.parse(JSON.stringify(template.data));
  rowCount.value = template.rowCount;
  columnCount.value = template.columnCount;

  templateListVisible.value = false;
  selectedTemplate.value = null;

  Message.success("模板加载成功");
};

// 删除模板
const deleteTemplate = (templateId) => {
  try {
    // 删除本地模板
    const templates = JSON.parse(
      localStorage.getItem("excelTemplates") || "[]"
    );
    const filteredTemplates = templates.filter((t) => t.id !== templateId);
    localStorage.setItem("excelTemplates", JSON.stringify(filteredTemplates));

    loadSavedTemplates();
    Message.success("模板删除成功");
  } catch (error) {
    console.error("删除模板失败:", error);
    Message.error("删除模板失败，请重试");
  }
};

// 清空表格
const clearAll = () => {
  templateName.value = "新建表格模板";
  rowCount.value = 5;
  columnCount.value = 5;
  selectedRowKeys.value = [];
  selectedColumnKeys.value = [];
  initTable();
  Message.success("表格已清空");
};

// 组件挂载时初始化
onMounted(() => {
  // 优先加载从演示页面传递的模板
  const selectedTemplate = sessionStorage.getItem("selectedTemplate");
  if (selectedTemplate) {
    try {
      const template = JSON.parse(selectedTemplate);
      templateName.value = template.templateName;
      rowCount.value = template.rowCount;
      columnCount.value = template.columnCount;

      // 初始化表格
      initTable();

      // 设置列标题
      template.columns.forEach((col, index) => {
        if (index < columnCount.value) {
          tableColumns.value[index].title = col.title;
        }
      });

      // 设置数据行
      template.data.forEach((row, rowIndex) => {
        if (rowIndex < rowCount.value) {
          template.columns.forEach((col, colIndex) => {
            if (colIndex < columnCount.value) {
              tableData.value[rowIndex][
                tableColumns.value[colIndex].dataIndex
              ] = row[col.dataIndex] || "";
            }
          });
        }
      });

      // 清除sessionStorage中的模板数据
      sessionStorage.removeItem("selectedTemplate");
      Message.success(`已加载${template.templateName}模板`);
    } catch (error) {
      console.error("加载示例模板失败:", error);
      initTable();
    }
  } else {
    initTable();
  }

  loadSavedTemplates();
});
</script>

<style scoped>
.excel-template-designer {
  padding: 16px;
}

.toolbar {
  margin-bottom: 16px;
  padding: 16px;
  background: #f5f5f5;
  border-radius: 6px;
}

.table-container {
  border: 1px solid #e5e5e5;
  border-radius: 6px;
  overflow: auto;
}

.editable-table {
  background: white;
}

.column-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.property-panel {
  margin-top: 16px;
}

.preview-content {
  max-height: 500px;
  overflow: auto;
}

:deep(.arco-table-th) {
  background: #f7f8fa;
}

:deep(.arco-table-td) {
  padding: 4px 8px;
}

:deep(.arco-input) {
  border: none;
  background: transparent;
}

:deep(.arco-input:focus) {
  border: 1px solid #165dff;
  background: white;
}
</style>
